<template>
  <el-dialog
    v-model="visible"
    title="⚠️ 删除维度 - 影响分析"
    width="700px"
    destroy-on-close
    :before-close="handleBeforeClose"
  >
    <div v-loading="loading" class="delete-container">
      <div class="dimension-name">
        即将删除维度: {{ dimension.name || "" }} ({{ dimension.code || "" }})
      </div>

      <!-- 依赖关系检查 -->
      <el-card class="delete-section-card">
        <template #header>
          <span class="section-title">依赖关系检查</span>
        </template>
        <div class="dependency-check">
          <div class="check-result">
            🔍 该维度代码被 {{ dependentTemplates.length }} 个模板使用
          </div>

          <div
            v-for="(template, index) in dependentTemplates"
            :key="index"
            class="dependent-template"
          >
            <div class="template-header">
              <el-tag
                :type="template.status === '启用中' ? 'warning' : 'info'"
                size="small"
                class="status-tag"
              >
                {{ template.status === "启用中" ? "⚠️" : "ℹ️" }}
                {{ template.name }} ({{ template.status }})
              </el-tag>
            </div>
            <div class="template-details">
              <div v-if="template.asset_count">
                • 正在被 {{ template.asset_count }} 个资产使用
              </div>
              <div v-if="template.score_contribution">
                • 该维度贡献最高 {{ template.score_contribution }} 分 ({{
                  template.max_score
                }}×{{ template.weight }})
              </div>
              <div v-if="template.percentage">
                • 占模板总分的 {{ template.percentage }}
              </div>
              <div v-if="!template.asset_count">• 模板未启用，暂无资产使用</div>
              <div v-if="!template.asset_count">• 影响较小</div>
            </div>
          </div>

          <div v-if="dependentTemplates.length === 0" class="no-dependencies">
            该维度未被任何模板使用
          </div>
        </div>
      </el-card>

      <!-- 删除后果 -->
      <el-card class="delete-section-card danger-card">
        <template #header>
          <span class="section-title">删除后果</span>
        </template>
        <div class="consequences">
          <div class="consequence-title">🚨 警告: 此操作将导致以下影响</div>

          <div class="consequence-section">
            <div class="section-title">直接影响:</div>
            <ul class="consequence-list">
              <li v-for="(item, index) in directConsequences" :key="index">
                {{ item }}
              </li>
            </ul>
          </div>

          <div class="consequence-section">
            <div class="section-title">历史数据:</div>
            <ul class="consequence-list">
              <li v-for="(item, index) in historyConsequences" :key="index">
                {{ item }}
              </li>
            </ul>
          </div>

          <div class="consequence-section" v-if="dependentTemplates.length > 0">
            <div class="section-title">其他影响:</div>
            <ul class="consequence-list">
              <li v-for="(item, index) in otherConsequences" :key="index">
                {{ item }}
              </li>
            </ul>
          </div>
        </div>
      </el-card>

      <!-- 安全选项 -->
      <el-card class="delete-section-card">
        <template #header>
          <span class="section-title">安全选项</span>
        </template>
        <div class="safety-options">
          <div class="option-title">建议操作:</div>

          <el-radio-group v-model="deleteOption">
            <el-radio label="disable_only" class="radio-option">
              <div class="option-content">
                <div class="option-name">仅禁用维度 (推荐)</div>
                <div class="option-description">
                  → 维度将停止参与评分，但配置保留<br />
                  → 随时可以重新启用
                </div>
              </div>
            </el-radio>

            <el-radio label="export_and_delete" class="radio-option">
              <div class="option-content">
                <div class="option-name">先导出配置，再删除</div>
                <div class="option-description">
                  → 导出JSON配置文件作为备份<br />
                  → 然后执行删除操作
                </div>
              </div>
            </el-radio>

            <el-radio label="force_delete" class="radio-option danger-option">
              <div class="option-content">
                <div class="option-name">强制删除 (不推荐)</div>
                <div class="option-description">
                  → 立即删除，无法恢复<br />
                  → 需要输入维度代码确认
                </div>
              </div>
            </el-radio>
          </el-radio-group>
        </div>
      </el-card>

      <!-- 确认删除 -->
      <el-card
        class="delete-section-card confirm-card"
        v-if="
          deleteOption === 'export_and_delete' ||
          deleteOption === 'force_delete'
        "
      >
        <template #header>
          <span class="section-title">确认删除</span>
        </template>
        <div class="confirm-options">
          <el-checkbox v-model="confirmUnderstand" class="confirm-checkbox">
            我已了解删除后果
          </el-checkbox>

          <el-checkbox
            v-model="confirmExported"
            class="confirm-checkbox"
            v-if="deleteOption === 'export_and_delete'"
          >
            我已导出备份配置
          </el-checkbox>

          <el-checkbox v-model="confirmDelete" class="confirm-checkbox">
            我确认要删除此维度
          </el-checkbox>

          <div v-if="deleteOption === 'force_delete'" class="code-confirmation">
            <div class="confirmation-label">最终确认，请输入维度代码:</div>
            <el-input
              v-model="confirmationCode"
              placeholder="请输入维度代码"
              class="code-input"
              :disabled="!confirmDelete || !confirmUnderstand"
            ></el-input>
            <div
              v-if="confirmationCode && confirmationCode !== dimension.code"
              class="code-error"
            >
              输入的维度代码不正确
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button
        type="default"
        @click="emit('only-disable')"
        :disabled="deleteOption !== 'disable_only'"
      >
        仅禁用
      </el-button>
      <el-button
        type="primary"
        @click="handleExportAndDelete"
        :disabled="
          deleteOption !== 'export_and_delete' ||
          !confirmUnderstand ||
          !confirmExported ||
          !confirmDelete
        "
      >
        导出并删除
      </el-button>
      <el-button
        type="danger"
        @click="emit('confirm-delete')"
        :disabled="
          deleteOption !== 'force_delete' ||
          !confirmUnderstand ||
          !confirmDelete ||
          confirmationCode !== dimension.code
        "
      >
        强制删除(需确认)
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
// import { getDimensionDependencies } from "../../../servers";

// 定义属性和事件
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  dimension: {
    type: Object,
    default: () => ({
      id: "",
      name: "",
      code: "",
      max_score: 0,
      weight: 0,
    }),
  },
});

const emit = defineEmits([
  "confirm-delete",
  "only-disable",
  "export-and-delete",
  "update:modelValue",
]);

// 响应式数据
const visible = ref(props.modelValue);
const loading = ref(false);
const dependentTemplates = ref([]);
const deleteOption = ref("disable_only");
const confirmUnderstand = ref(false);
const confirmExported = ref(false);
const confirmDelete = ref(false);
const confirmationCode = ref("");

// 直接影响
const directConsequences = computed(() => {
  const consequences = [];
  dependentTemplates.value.forEach((template) => {
    consequences.push(
      `✗ ${template.name}将缺少 "${props.dimension.name}" 维度`
    );
  });

  const hasEnabledTemplates = dependentTemplates.value.some(
    (t) => t.status === "启用中"
  );
  if (hasEnabledTemplates) {
    consequences.push(`✗ 相关资产的风险评分将立即重新计算`);
    consequences.push(
      `✗ 所有资产的总分将减少 0-${
        (props.dimension.max_score || 0) * (props.dimension.weight || 0)
      } 分`
    );
    consequences.push(`✗ 可能导致部分资产的风险等级下降`);
  }

  return consequences.length > 0
    ? consequences
    : ["✗ 该维度将从系统中永久删除"];
});

// 历史数据影响
const historyConsequences = [
  "⚠️ 历史评分记录将保留但无法重新计算",
  "⚠️ 该维度的历史趋势数据将无法查看",
];

// 其他影响
const otherConsequences = computed(() => {
  const consequences = [];
  if (dependentTemplates.length > 1) {
    consequences.push(`⚠️ 所有关联模板也将失去该维度配置`);
  }
  consequences.push(`⚠️ 无法恢复，建议先导出配置备份`);
  return consequences;
});

// 监听显示状态变化
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
    if (val && props.dimension.id) {
      fetchDependencies();
    }
  }
);

// 监听维度变化
watch(
  () => props.dimension,
  (dimension) => {
    if (dimension.id && visible.value) {
      fetchDependencies();
    }
  }
);

// 监听删除选项变化
watch(
  () => deleteOption.value,
  (option) => {
    // 重置确认状态
    confirmUnderstand.value = false;
    confirmExported.value = false;
    confirmDelete.value = false;
    confirmationCode.value = "";
  }
);

// 页面初始化
onMounted(() => {
  if (props.dimension.id && visible.value) {
    fetchDependencies();
  }
});

// 获取依赖关系
const fetchDependencies = async () => {
  // loading.value = true;
  // try {
  //   const { data } = await getDimensionDependencies({ id: props.dimension.id });
  //   dependentTemplates.value = data.templates || [];
  // } catch (error) {
  //   ElMessage.error("获取依赖关系失败");
  // } finally {
  //   loading.value = false;
  // }
};

// 导出并删除
const handleExportAndDelete = () => {
  // 先执行导出操作
  ElMessage.success("配置已导出");
  emit("export-and-delete");
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};

// 关闭前处理
const handleBeforeClose = () => {
  emit("update:modelValue", false);
  return true;
};
</script>
<style scoped lang="scss">
.delete-container {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.dimension-name {
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 16px;
  padding: 10px;
  background-color: #fff1f0;
  border-radius: 6px;
  color: #f5222d;
}

.delete-section-card {
  margin-bottom: 16px;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.section-title {
  font-weight: 500;
  color: #1d2129;
}

.danger-card {
  border-left: 4px solid #f5222d;
}

.dependency-check {
  padding: 5px 0;
}

.check-result {
  margin-bottom: 15px;
  font-weight: 500;
  color: #f5222d;
}

.dependent-template {
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 4px;
  background-color: #f9f9f9;

  &:last-child {
    margin-bottom: 0;
  }
}

.template-header {
  margin-bottom: 8px;
}

.status-tag {
  padding: 2px 8px;
}

.template-details {
  padding-left: 25px;
  font-size: 13px;
  line-height: 1.6;
}

.no-dependencies {
  padding: 15px;
  text-align: center;
  color: #86909c;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.consequences {
  padding: 5px 0;
}

.consequence-title {
  color: #f5222d;
  font-weight: 500;
  margin-bottom: 15px;
  font-size: 14px;
}

.consequence-section {
  margin-bottom: 15px;

  &:last-child {
    margin-bottom: 0;
  }
}

.consequence-section .section-title {
  margin-bottom: 8px;
  font-size: 13px;
  color: #f5222d;
}

.consequence-list {
  padding-left: 20px;
  font-size: 13px;
  line-height: 1.6;

  li {
    margin-bottom: 5px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.safety-options {
  padding: 5px 0;
}

.option-title {
  font-weight: 500;
  margin-bottom: 15px;
  color: #1d2129;
}

.radio-option {
  display: block;
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 4px;
  background-color: #f9f9f9;

  &:last-child {
    margin-bottom: 0;
  }
}

.option-content {
  margin-left: 25px;
}

.option-name {
  font-weight: 500;
  margin-bottom: 5px;
}

.option-description {
  font-size: 13px;
  color: #666;
  line-height: 1.6;
}

.danger-option {
  background-color: #fff1f0;
  border-left: 3px solid #f5222d;
}

.confirm-card {
  border-left: 4px solid #faad14;
}

.confirm-options {
  padding: 5px 0;
}

.confirm-checkbox {
  display: block;
  margin-bottom: 10px;
}

.code-confirmation {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #e5e6eb;
}

.confirmation-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #f5222d;
}

.code-input {
  width: 100%;
  margin-bottom: 5px;
}

.code-error {
  font-size: 12px;
  color: #f5222d;
}
</style>
